"""
插件框架命令行工具
提供插件管理的命令行接口
"""

import os
import sys
import argparse
import logging

# 添加项目根目录到路径
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))

from plugin_framework.plugin_manager import PluginManager
from plugin_framework.api_context import APIContext


def setup_logging(level=logging.INFO):
    """设置日志"""
    logging.basicConfig(
        level=level,
        format='%(asctime)s - %(levelname)s - %(message)s'
    )


def list_plugins(manager):
    """列出所有插件"""
    print("=== 插件列表 ===")
    
    # 扫描插件
    discovered = manager.scan()
    
    if not discovered:
        print("未发现任何插件")
        return
    
    print(f"发现 {len(discovered)} 个插件:")
    for plugin_name in discovered:
        config = manager.get_config(plugin_name)
        status = "已加载" if manager.is_loaded(plugin_name) else "未加载"
        if config:
            print(f"  - {plugin_name} v{config.version} ({status})")
            print(f"    作者: {config.author}")
            print(f"    描述: {config.description}")
            print()


def load_plugin(manager, plugin_name):
    """加载插件"""
    try:
        # 先扫描插件确保配置被加载
        manager.scan()
        plugin = manager.load(plugin_name)
        print(f"✓ 插件 '{plugin_name}' 加载成功")
        return plugin
    except Exception as e:
        print(f"✗ 加载插件 '{plugin_name}' 失败: {e}")
        return None


def unload_plugin(manager, plugin_name):
    """卸载插件"""
    try:
        success = manager.unload(plugin_name)
        if success:
            print(f"✓ 插件 '{plugin_name}' 卸载成功")
        else:
            print(f"✗ 插件 '{plugin_name}' 卸载失败")
    except Exception as e:
        print(f"✗ 卸载插件 '{plugin_name}' 失败: {e}")


def enable_plugin(manager, plugin_name):
    """启用插件"""
    try:
        # 先扫描插件确保配置被加载
        manager.scan()
        success = manager.enable(plugin_name)
        if success:
            print(f"✓ 插件 '{plugin_name}' 启用成功")
        else:
            print(f"✗ 插件 '{plugin_name}' 启用失败")
    except Exception as e:
        print(f"✗ 启用插件 '{plugin_name}' 失败: {e}")


def disable_plugin(manager, plugin_name):
    """禁用插件"""
    try:
        success = manager.disable(plugin_name)
        if success:
            print(f"✓ 插件 '{plugin_name}' 禁用成功")
        else:
            print(f"✗ 插件 '{plugin_name}' 禁用失败")
    except Exception as e:
        print(f"✗ 禁用插件 '{plugin_name}' 失败: {e}")


def reload_plugin(manager, plugin_name):
    """重新加载插件"""
    try:
        # 先扫描插件确保配置被加载
        manager.scan()
        plugin = manager.reload(plugin_name)
        print(f"✓ 插件 '{plugin_name}' 重新加载成功")
        return plugin
    except Exception as e:
        print(f"✗ 重新加载插件 '{plugin_name}' 失败: {e}")
        return None


def run_plugin(manager, plugin_name, **kwargs):
    """运行插件"""
    try:
        # 先扫描插件确保配置被加载
        manager.scan()
        plugin = manager.get(plugin_name)
        if not plugin:
            # 如果插件未加载，尝试加载它
            plugin = manager.load(plugin_name)
            if not plugin:
                print(f"✗ 插件 '{plugin_name}' 加载失败")
                return
        
        result = plugin.run(**kwargs)
        print(f"插件运行结果: {result}")
        return result
    except Exception as e:
        print(f"✗ 运行插件 '{plugin_name}' 失败: {e}")


def main():
    """主函数"""
    parser = argparse.ArgumentParser(description="插件框架命令行工具")
    parser.add_argument("--plugin-dir", default="./plugins", help="插件目录路径")
    parser.add_argument("--verbose", "-v", action="store_true", help="详细输出")
    
    subparsers = parser.add_subparsers(dest="command", help="命令")
    
    # list 命令
    subparsers.add_parser("list", help="列出所有插件")
    
    # load 命令
    load_parser = subparsers.add_parser("load", help="加载插件")
    load_parser.add_argument("plugin_name", help="插件名称")
    
    # unload 命令
    unload_parser = subparsers.add_parser("unload", help="卸载插件")
    unload_parser.add_argument("plugin_name", help="插件名称")
    
    # enable 命令
    enable_parser = subparsers.add_parser("enable", help="启用插件")
    enable_parser.add_argument("plugin_name", help="插件名称")
    
    # disable 命令
    disable_parser = subparsers.add_parser("disable", help="禁用插件")
    disable_parser.add_argument("plugin_name", help="插件名称")
    
    # reload 命令
    reload_parser = subparsers.add_parser("reload", help="重新加载插件")
    reload_parser.add_argument("plugin_name", help="插件名称")
    
    # run 命令
    run_parser = subparsers.add_parser("run", help="运行插件")
    run_parser.add_argument("plugin_name", help="插件名称")
    run_parser.add_argument("--args", nargs="*", help="传递给插件的参数")
    
    args = parser.parse_args()
    
    # 设置日志级别
    log_level = logging.DEBUG if args.verbose else logging.INFO
    setup_logging(log_level)
    
    # 创建插件管理器
    plugin_dir = os.path.abspath(args.plugin_dir)
    api_context = APIContext("CLI")
    manager = PluginManager(plugin_dir, api_context)
    
    # 执行命令
    if args.command == "list":
        list_plugins(manager)
    elif args.command == "load":
        load_plugin(manager, args.plugin_name)
    elif args.command == "unload":
        unload_plugin(manager, args.plugin_name)
    elif args.command == "enable":
        enable_plugin(manager, args.plugin_name)
    elif args.command == "disable":
        disable_plugin(manager, args.plugin_name)
    elif args.command == "reload":
        reload_plugin(manager, args.plugin_name)
    elif args.command == "run":
        # 解析参数
        kwargs = {}
        if args.args:
            for arg in args.args:
                if "=" in arg:
                    key, value = arg.split("=", 1)
                    kwargs[key] = value
                else:
                    kwargs[arg] = True
        run_plugin(manager, args.plugin_name, **kwargs)
    else:
        parser.print_help()


if __name__ == "__main__":
    # 确保在正确的目录下运行
    script_dir = os.path.dirname(os.path.abspath(__file__))
    os.chdir(script_dir)
    main()